<template>
  <div id="app">
    <router-view />
  </div>
</template>

<script>
import { mapState, mapMutations } from "vuex";
import pinyin from "js-pinyin";
import audioMsg from "./assets/msg.mp3";
import audioTips from "./assets/tips.mp3";
import store from "./store/index";

export default {
  name: "App",
  data() {
    return {
      active: 0,
      num: 20,
      dot: true,
      socket: null,
      time: null,
      indexList: [
        "A",
        "B",
        "C",
        "D",
        "E",
        "F",
        "G",
        "H",
        "I",
        "J",
        "K",
        "L",
        "M",
        "O",
        "P",
        "Q",
        "R",
        "S",
        "T",
        "U",
        "V",
        "W",
        "X",
        "Y",
        "Z",
        "#"
      ],
      retry: 1,
      load: null
    };
  },
  methods: {
    ...mapMutations(["updateWsIsLive"]),
    init() {
      const that = this;
      if ("WebSocket" in window) {
        // 打开一个 websocket
        var ws = new WebSocket(this.server.WS + "/" + this.token);

        ws.onopen = function() {
          // WebSocket 已连接上，使用 send() 方法发送数据
          if (ws.readyState == 1) {
            that.socket = ws;
            that.updateWsIsLive(true);
            if (that.retry != 1) {
              that.load.clear();
              that.$toast("连接成功");
            }
            that.retry = 1;
          }
        };

        ws.onmessage = function(evt) {
          let data = JSON.parse(evt.data);
          console.log(data);
          if (data.type == "conn") {
            console.log(data.data);
          } else if (data.type == "request") {
            let userInfo = data.data;
            if (userInfo.status == 1) {
              let voice = new Audio(audioTips);
              voice.play();
              that.$notify({
                type: "success",
                message: userInfo.userName + "请求添加好友!"
              });
              let requestFriend = store.state.requestFriend;
              requestFriend.push(userInfo);
              store.dispatch("asyncSaveRequest", requestFriend);
            } else if (userInfo.status == 2) {
              let voice = new Audio(audioTips);
              voice.play();
              that.$notify({
                type: "success",
                message: userInfo.userName + "好友请求已通过"
              });
              let contactList = store.state.contactList;
              let firstChart = that.getFirstLetter(userInfo.userName);
              let index = that.getIndexBar(firstChart);
              let tempUser = {
                userId: userInfo.userId,
                userName: userInfo.userName,
                userImg: userInfo.userImg
              };
              contactList[index].push(tempUser);
              store.dispatch("asyncSaveContactList", contactList);
            } else if (userInfo.status == 3) {
              let voice = new Audio(audioTips);
              voice.play();
              that.$notify({
                type: "warning",
                message: userInfo.userName + "好友请求被拒绝"
              });
            }
          } else if (data.type == "ping") {
            that.ping = true;
          } else if (data.type == "chat") {
            let msgData = data.data;
            if (!store.state.isChatting) {
              let voice = new Audio(audioMsg);
              voice.play();
              that.$notify({
                type: "primary",
                message:
                  "收到 " + msgData.fromUserName + "的消息 : " + msgData.msg
              });
            }
            that.handleMessage(msgData);
          }
        };

        ws.onclose = function() {
          // 关闭 websocket
          console.log("连接已关闭...");
          that.updateWsIsLive(false);
          that.socket = null;
        };

        ws.onerror = function() {
          that.updateWsIsLive(false);
          if (that.retry > 1) {
            that.load.clear();
          }
          that.$notify({
            type: "danger",
            message: "服务器连接已断开！"
          });
          console.log("连接发生错误");
          if (that.retry <= 3) {
            that.$dialog
              .confirm({
                message: "是否重新连接？",
                showCancelButton: true,
                confirmButtonText: that.retry == 1 ? "重连" : "重试",
                confirmButtonColor: "#ee0a24"
              })
              .then(() => {
                that.retry++;
                that.load = that.$toast.loading({
                  duration: 0,
                  message: "连接中...",
                  forbidClick: true
                });
                that.init();
              })
              .catch(() => {});
          } else {
            that.$dialog
              .confirm({
                message: "貌似问题有点大，建议重新登录哦...",
                showCancelButton: true,
                confirmButtonText: "重新登录",
                confirmButtonColor: "#ee0a24"
              })
              .then(() => {
                that.$router.push("/login");
              })
              .catch(() => {});
          }
        };
      } else {
        // 浏览器不支持 WebSocket
        alert("您的浏览器不支持 WebSocket!");
      }
    },
    getFirstLetter(character) {
      return pinyin
        .getCamelChars(character)
        .substr(0, 1)
        .toUpperCase();
    },
    getIndexBar(chart) {
      let num = this.indexList.length - 1;
      this.indexList.forEach((item, index) => {
        if (item == chart) {
          num = index;
        }
      });
      //未找到分类的都视为#类型
      return num;
    },
    handleMessage(msgData) {
      let list = store.state.chatList;
      //判断列表是否为空
      if (list.length > 0) {
        let exist = false;
        list.forEach(element => {
          //已有聊天信息，更新数据
          if (element.friendId == msgData.fromUserId) {
            exist = true;
            if (store.state.isChatting) {
              msgData.read = true;
              element.count = 0;
            } else {
              element.count++;
            }
            element.lastMsg = msgData.msg;
            element.lastMsgTime = msgData.time;
            element.msgList.push(msgData);
          }
        });

        //没有聊天数据，增加新的聊天数据
        if (!exist) {
          let msgList = [];
          if (store.state.isChatting) {
            msgData.read = true;
          }
          msgList.push(msgData);
          let chatData = {
            count: 1,
            lastMsg: msgData.msg,
            lastMsgTime: msgData.time,
            friendId: msgData.fromUserId,
            friendUserName: msgData.fromUserName,
            friendUserImg: msgData.fromUserImg,
            msgList: msgList
          };
          if (store.state.isChatting) {
            chatData.count = 0;
          }
          list.push(chatData);
        }
      } else {
        //初始化列表数据
        let msgList = [];
        if (store.state.isChatting) {
          msgData.read = true;
        }
        msgList.push(msgData);
        let chatData = {
          count: 1,
          lastMsg: msgData.msg,
          lastMsgTime: msgData.time,
          friendId: msgData.fromUserId,
          friendUserName: msgData.fromUserName,
          friendUserImg: msgData.fromUserImg,
          msgList: msgList
        };
        if (store.state.isChatting) {
          chatData.count = 0;
        }
        list.push(chatData);
      }
      store.dispatch("asyncSaveChatList", list);
    },
    //心跳检查
    healthPing() {
      const that = this;
      let message = {
        type: "ping",
        data: "心跳检查"
      };
      that.time = setInterval(() => {
        that.ping = false;
        try {
          that.socket.send(JSON.stringify(message));
        } catch (error) {
          console.log(error);
          if (that.retry > 1) {
            that.load.clear();
          }
          that.$notify({
            type: "danger",
            message: "服务器连接已断开！"
          });
          console.log("连接发生错误");
          if (that.retry <= 3) {
            that.$dialog
              .confirm({
                message: "是否重新连接？",
                showCancelButton: true,
                confirmButtonText: that.retry == 1 ? "重连" : "重试",
                confirmButtonColor: "#ee0a24"
              })
              .then(() => {
                that.retry++;
                that.load = that.$toast.loading({
                  duration: 0,
                  message: "连接中...",
                  forbidClick: true
                });
                that.init();
              })
              .catch(() => {});
          } else {
            that.$dialog
              .confirm({
                message: "貌似问题有点大，建议重新登录哦...",
                showCancelButton: true,
                confirmButtonText: "重新登录",
                confirmButtonColor: "#ee0a24"
              })
              .then(() => {
                that.$router.push("/login");
              })
              .catch(() => {});
          }
        }
      }, 15000);
    }
  },
  created() {
    if (this.token.length > 0) {
      if (!this.wsIsLive && this.user.userId != null) {
        this.init();
        this.healthPing();
      }
    }
  },
  destroyed() {
    if (this.time != null) {
      clearInterval(this.time);
    }
    if (this.socket != null) {
      this.socket.close();
    }
  },
  computed: {
    ...mapState(["user", "wsIsLive", "token"])
  }
};
</script>

<style lang="scss">
body {
  background-color: #ffffff;
}
</style>
